<template>
  <el-dialog
    v-model="obj.dialogVisible"
    :title="obj.id === 0 ? '新增分类' : '修改分类'"
    width="500"
    :before-close="handleClose"
  >
    <span>
      <el-form
        :model="form"
        label-width="auto"
        style="max-width: 600px"
        ref="refFrom"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 240px"
            placeholder="请输入分类名称"
          />
        </el-form-item>

        <el-form-item label="分类等级" prop="denJi">
          <el-radio-group v-model="form.denJi">
            <el-radio :label="1">一级分类</el-radio>
            <el-radio :label="2">二级分类</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上传图片" prop="tuPian" v-show="form.denJi === 2">
          <el-upload
            ref="loadRef"
            class="upload-demo"
            drag
            v-model="form.tuPian"
            action="http://localhost:8080/category/uploadImage"
            :headers="{
              token
            }"
            :data="{
              type: 'category_picture'
            }"
            multiple
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              请将图片拖拽至此 或 <em>点击浏览图片</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                请上传jpg或png格式的文件，并且大小最大不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item label="分类选择" v-show="form.denJi === 2" prop="select">
          <el-select
            v-model="form.select"
            placeholder="请选择分类等级"
            style="width: 150px"
          >
            <el-option
              :label="it.name"
              :value="it.id"
              v-for="it in showList"
              :key="it.id"
              :v-if="it.pid === 0"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="emits('close')">关闭</el-button>
        <el-button @click="chongZhi">重置</el-button>
        <el-button type="primary" @click="addObj"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
</style>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessageBox } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { add, update } from '../api/apiByCategory.js';
import { useTokenStore } from '../store/tokenStore.js';
import  message  from '../utils/message.js';

const { token } = useTokenStore();

const refFrom = ref(null);
const form = reactive({
  id: 0,
  name: '',
  //等级
  denJi: 1,
  //图片
  tuPian: '',
  //父级
  select: 0
});

const change = async (data) => {
  
  if (data.errno === 0) {
    if (data.errmsg != '') {
      message({
        message: data.errmsg,
        type: 'success'
      });
    }
    form.tuPian = data.data;
    return;
  }
  if (data.errmsg != '') {
    message({
      message: data.errmsg,
      type: 'error'
    });
  }
  if (data.errno === 2) {
    router.push('/');
  }
};

const handleSuccess = (response, file, fileList)=> {
      // response 是服务器返回的数据
      console.log('上传成功:', response);
      // 可以在这里处理返回的数据，例如更新表单字段
      change(response);
    }
const handleError =(err, file, fileList) =>{
      // err 是错误信息
      console.error('图片上传失败:', err);
      // 可以在这里处理错误信息
      message({
    message: '图片上传失败，请检查图片格式和大小',
    type: 'error'
  });
    }

const obj = defineProps({
  dialogVisible: {
    type: Boolean
  },
  list: {
    type: Array
  },
  good: {
    type: Object,
    required: true
  },
  id: {
    type: Number
  }
});

const showList = ref([]);

// 监听 dialogVisible 变化
watch(
  () => obj.dialogVisible,
  (newValue) => {
    if (newValue) {
      showList.value = obj.list.filter((item) => item.pid === 0);
      form.name = obj.good.name;
      form.id = obj.good.id;
      if (obj.good.pid === 0) {
        form.denJi = 1;
        form.select = showList.value[0].id;
      } else {
        form.select = obj.good.pid;
        form.denJi = 2;
      }
      form.tuPian = obj.good.picture;
    }
  }
);

const emits = defineEmits();
const handleClose = () => {
  ElMessageBox.confirm('确定要关闭此对话框么', {
    showClose: false,
    closeOnClickModal: false,
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
    .then(() => {
      emits('close');
    })
    .catch(() => {
      // catch error
    });
};

//表单重置功能，暴露给父组件调用
const chongZhi = () => {
  refFrom.value.resetFields();
};
defineExpose({ chongZhi });

const addObj = async () => {
  if (obj.id == 0) {
    await add({
      name: form.name,
      pid: form.denJi === 1 ? 0 : form.select,
      picture: form.tuPian
    });
  } else {
    await update({
      id: obj.id,
      name: form.name,
      pid: form.denJi === 1 ? 0 : form.select,
      picture: form.tuPian
    });
  }
  emits('add');
};
</script>

